<?php

namespace App\Http\Requests;

use Illuminate\Database\Query\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CnDiagnoseStoreRequest extends FormRequest
{
    protected $diagnose;

    /**
     * Prepare the data for validation.
     * @return void
     */
    protected function prepareForValidation()
    {
        $this->diagnose = app('field')->get('diagnose.cn_diagnose');
    }

    /**
     * Determine if the user is authorized to make this request.
     * @return bool
     */
    public function authorize()
    {
        return \Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     * @return array
     */
    public function rules()
    {
        return [
            'record_id'     => [
                'required', 'integer', 'min:1',
                Rule::exists('st_medical_records', 'id')->where(function (Builder $query) {
                    $query->whereNull('deleted_at');
                    $user = \Auth::user();
                    if (!$user->isDoctorsAdmin() && !$user->isAdmin()) {
                        $query->where(['doctor_id' => $user->id]);
                    }
                }),
            ],
            'cn_disease_id' => [
                'required', 'integer', 'min:1',
                Rule::exists('st_cn_disease_dictionary', 'id')->whereNull('deleted_at')
            ],
            'type_id'       => [
                'integer', 'in:' . implode(',', array_keys($this->diagnose['type']))
            ],
            'carry_key.*'   => 'in:' . implode(',', array_keys($this->diagnose['carry']))
        ];
    }
}
